package com.sinoair.web;

import com.sinoair.domain.User;
import com.sinoair.exception.MyException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


@Controller
public class IndexController {

    protected static Logger logger = LoggerFactory.getLogger(IndexController.class);

    @RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
    public String home(Model model) {

        logger.debug("主页index");
        //从shiro的session中取activeUser
        Subject subject = SecurityUtils.getSubject();
        //取身份信息
        User adminUser = (User) subject.getPrincipal();
        //通过model传到页面
        model.addAttribute("adminUser", adminUser);

        return "index";
    }

    /**
     * 退出
     *
     * @return
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @ResponseBody
    public String logout(RedirectAttributes redirectAttributes) {
        try {
            //使用权限管理工具进行用户的退出，跳出登录，给出提示信息
            SecurityUtils.getSubject().logout();
            redirectAttributes.addFlashAttribute("message", "您已安全退出");
            return "redirect:login";
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return "redirect:login";
    }

    @RequestMapping("/403")
    public String unauthorizedRole() {
        logger.info("------没有权限-------");
        return "errorPermission";
    }


    @ResponseBody
    @RequestMapping(value = "/helloErr", method = RequestMethod.GET)
    public String hello() throws Exception {
        throw new Exception("发生错误");
    }

    @ResponseBody
    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String json() throws MyException {
        throw new MyException("发生错误2");
    }

}
